import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_video_course.dart';
import 'package:flutter_learn_vi/src/page/mine/mine_study_recoder_progress_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:get/get.dart';

import '../../bean/bean_train.dart';
import '../../common/user_helper.dart';
import '../../face/face_detector_view.dart';
import '../../net/dio_utils.dart';
import '../../utils/toast_utils.dart';
import '../study/course/course_sign_list_page.dart';
import '../study/course/main_course_page.dart';
import '../trainnew/train_line_course_details_controller.dart';
import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/14.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainTeacherCourseVideoItemWidget extends StatefulWidget {
  final BeanVideoCourse beanVideoCourse;
  final int trainId;
  final TrainBean trainBean;
  final int index;

  final isScaffold;

  ///用户的学习记录
  final UserTrainStudyEntity userJoinTrainBean;

  ///默认false 与 [userJoinTrainBean]联合使用
  final bool isRequireUserJoin;

  /// 是否启用培训签到 on 开启；off 不开启
  final String openSign;

  const TrainTeacherCourseVideoItemWidget({
    Key key,
    this.beanVideoCourse,
    @required this.trainId,
    this.userJoinTrainBean,
    this.isRequireUserJoin = false,
    this.index,
    this.openSign = "off",
    this.isScaffold = true,
    this.trainBean,
  }) : super(key: key);

  @override
  _TrainTeacherCourseVideoItemWidgetState createState() =>
      _TrainTeacherCourseVideoItemWidgetState();
}

class _TrainTeacherCourseVideoItemWidgetState
    extends State<TrainTeacherCourseVideoItemWidget>
    with SingleTickerProviderStateMixin, TrainModel {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  bool faceImageLoading = false;
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 6),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              ClipOval(
                child: Container(
                  alignment: Alignment.center,
                  width: 14,
                  height: 14,
                  child: Text(
                    "${widget.index + 1}",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                  decoration: BoxDecoration(
                      gradient: LinearGradient(colors: [
                    Colors.blueAccent,
                    Colors.lightBlueAccent,
                    Colors.blue,
                  ])),
                ),
              ),
              SizedBox(
                width: 8,
              ),
              Expanded(
                  child: Text("${widget.beanVideoCourse.videoCourseName}")),
              SizedBox(
                width: 8,
              ),
              Icon(Icons.arrow_right),
            ],
          ),
          buildFlagContainer(),
          buildButtonRow(),
        ],
      ),
    );
  }

  Widget buildButtonRow() {
    ///未参与学习 不显示学习记录 、立即学习 按钮
    if (widget.isRequireUserJoin) {
      if (widget.userJoinTrainBean == null) {
        return SizedBox();
      }
    }
    return Row(
      children: [
        widget.openSign == "on"
            ? TextButton(
                onPressed: () {
                  debugPrint("点击---");
                  //MyStudyRecoderPage();
                  NavigatorUtils.pushPage(
                      context,
                      CourseSignAllListPage(
                        trainId: widget.trainId,
                        beanVideoCourse: widget.beanVideoCourse,
                      ));
                },
                child: Text("签到记录"),
              )
            : SizedBox(),
        TextButton(
          onPressed: () {
            UserStudyCourseBean userStudyCourseBean = new UserStudyCourseBean();
            userStudyCourseBean.videoCourseId = widget.beanVideoCourse.id;
            debugPrint("点击---");
            //MyStudyRecoderPage();
            NavigatorUtils.pushPage(
                context,
                MyStudyRecoderProgressPage(
                  trainId: widget.trainId,
                  courseBean: userStudyCourseBean,
                ));
          },
          child: Text("学习记录"),
        ),
        TextButton(
          onPressed: () async {
            //人脸识别

            String faceRecognition = widget.trainBean.faceRecognition;
            if (faceRecognition == "on") {
              if (faceImageLoading) {
                ToastUtils.showToast("正在识别中~~");
                return;
              }
              //自动识别的间隔时间 分钟
              int faceRecognitionTime = widget.trainBean.faceRecognitionTime;
              //分钟转秒
              int faceRecognitionTimeSeconds = faceRecognitionTime * 60;
              //测试使用
              //faceRecognitionTimeSeconds = 10;
              //如果本地时间大于人脸识别时间
              DateTime lastFaceRecognitionTime =
                  UserHelper.getInstance.lastFaceRecognitionTime;
              bool showDialog = false;
              if (lastFaceRecognitionTime == null) {
                showDialog = true;
              } else {
                //是否超出1分钟
                Duration duration =
                    DateTime.now().difference(lastFaceRecognitionTime);
                int seconds = duration.inSeconds;
                if (seconds > 60) {
                  showDialog = true;
                }
              }
              //培训完成后不需要人脸识别
              int trainStatus = widget.trainBean.trainStatus;
              if (trainStatus != 5) {
                debugPrint("非进行中的培训 不需要人脸识别~~");
                showDialog = false;
              }
              bool isShowFaceCheck = UserHelper.getInstance.isShowFaceCheck();
              if (!isShowFaceCheck) {
                debugPrint("指定人员 不需要人脸识别~~");
                showDialog = false;
              }

              if (showDialog) {
                debugPrint("需要开启人脸识别 ");
                dynamic result = await Get.defaultDialog(
                    title: "提示",
                    content: Container(
                        padding: EdgeInsets.only(top: 22, bottom: 22),
                        child: Text("本培训需要人脸识别认证")),
                    textCancel: "取消",
                    textConfirm: "去认证",
                    radius: 10,
                    onConfirm: () {
                      Get.back(result: true);
                    });
                if (result == null || !result) {
                  debugPrint("未选择去认证");
                  ToastUtils.showToast("需要认证后才能继续学习");
                  return;
                }
                //识别标记
                faceImageLoading = true;
                setState(() {});
                dynamic faceResult = await Get.to(() => FaceDetectorView(
                      key: UniqueKey(),
                    ));
                if (faceResult == null || faceResult.toString().isEmpty) {
                  ToastUtils.showToast("需要认证后才能继续学习");
                  //识别标记
                  faceImageLoading = false;
                  setState(() {});
                  return;
                }

                // String imageUrl = faceResult['imageUrl'] ?? '';
                // int imageLength = faceResult['imageLength'] ?? 0;
                // int uploadTime = faceResult['uploadTime'] ?? 0;
                // if (imageUrl.isEmpty) {
                //   ToastUtils.showToast("需要认证后才能继续学习");
                //   //识别标记
                //   faceImageLoading = false;
                //   setState(() {});
                //   return;
                // }
                //比对一下当前的人脸数据
                ResponseInfo statisRresponseInfo =
                    await DioUtils.instance.postRequest(
                  url: HttpHelper.compareFaceUrl,
                  encrypt: false,
                  jsonMap: {
                    "trainId": widget.trainId,
                    "faceType": "train",
                    "faceImageUrl": result.toString(),
                  },
                );
                //识别标记
                faceImageLoading = false;
                setState(() {});
                if (statisRresponseInfo.success) {
                  //识别成功 继续播放
                  debugPrint("人脸识别成功 继续播放");
                  UserHelper.getInstance.lastFaceRecognitionTime =
                      DateTime.now();
                } else {
                  await Get.defaultDialog(
                      radius: 10,
                      title: "人脸信息核定失败",
                      content: Text(statisRresponseInfo.message ?? "网络请求错误"),
                      textCancel: "关闭");
                  Get.back();
                  return;
                }
              }
            }

            await Get.to(
              () => MainCoursePage(
                beanVideoCourse: widget.beanVideoCourse,
                isTrainSign: true,
                openSign: widget.openSign,
                trainId: widget.trainId,
              ),
            );
            if (Get.isRegistered<TrainLineCourseDetailsController>(
                tag: "${widget.trainId}")) {
              TrainLineCourseDetailsController controller =
                  Get.find<TrainLineCourseDetailsController>(
                      tag: "${widget.trainId}");
              await controller.checkFinishTrainRequest(click: true);
              await controller.requestTrainDetails(loading: false);
            }
          },
          child: Text(
            faceImageLoading ? "正在认证中~~" : "立即学习",
            style: TextStyle(
              color: faceImageLoading ? Colors.red : Colors.blue,
            ),
          ),
        ),
      ],
      mainAxisAlignment: MainAxisAlignment.end,
    );
  }

  ///完成比例
  Widget buildFlagContainer() {
    ///未参与学习 不显示完成比例
    if (widget.isRequireUserJoin) {
      if (widget.userJoinTrainBean == null) {
        return SizedBox();
      }
    }
    return Container(
      padding: EdgeInsets.only(left: 22, top: 2),
      child: Row(
        children: [
          Text(
            "完成比例",
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
          Container(
            width: 100,
            height: 16,
            margin: EdgeInsets.only(left: 8, right: 8),
            child: Stack(
              children: [
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.all(Radius.circular(4))),
                  ),
                ),
                ClipRRect(
                  child: Align(
                    widthFactor: widget.beanVideoCourse.finishPrent,
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.green,
                          borderRadius: BorderRadius.all(Radius.circular(4))),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Text(
            "${(widget.beanVideoCourse.finishPrent * 100).toInt()}%",
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ],
      ),
    );
  }
}
